<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.text.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"   pageEncoding="ISO-8859-1"%>
<%@ include file="global.jsp" %>
<%
	boolean newUser = false;
	try{
		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String name = request.getParameter("fullName");
		String league = request.getParameter("league");
		String email = request.getParameter("email");
		
		
		
		System.out.println("userName ::" +userName);
		Class.forName(db_driver);
		Connection conn = DriverManager.getConnection(db_url, db_user, db_password);
        Statement stmt = conn.createStatement();
        PreparedStatement pstmt = null;
        int id = -1;
        System.out.println("STARTED");
		String str = "select count(*) from users where userName = '"+userName+"'";
		System.out.println("SQL: "+str);
		ResultSet rs = stmt.executeQuery(str);
		rs.next();          
		System.out.println("Number of rows :" + rs.getInt(1));
		id = rs.getInt(1);
		System.out.println("Id: "+id);
		
		
		if(id == 0){
			String query = "INSERT into users (userName, password, name, email, points, active, league) VALUES (?,?,?,?,?,?,?)";
			pstmt = conn.prepareStatement(query);
			pstmt.setString(1, userName);
			pstmt.setString(2, password);
			pstmt.setString(3, name);
			pstmt.setString(4, email);
			pstmt.setString(5, "0");
			pstmt.setInt(6, 0);
			pstmt.setString(7, league);
			pstmt.executeUpdate();
			newUser = true;
			session.setAttribute("resposeText","UserName '"+ userName +"' Created Succesfully");
			System.out.println("UserName "+ userName +" Created Succesfully");
			session.setAttribute("userName",userName);
			session.setAttribute("league",league);
		}else{
			newUser = false;
			session.setAttribute("errorMesg","Requested UserName '"+ userName +"'  Already Exists");
			//session.setAttribute("resposeText","Requested UserName '"+ userName +"'  Already Exists");
			//session.setAttribute("errorMesg",errorMesg);
			System.out.println("Requested UserName '"+ userName +"'  Already Exists");
		}
		rs.close();
		stmt.close();
        conn.close();
	}
 	catch ( Exception e1){
		e1.printStackTrace();
		session.setAttribute("errorMesg",e1.getMessage());
	} 
	finally{
		String errorMesg = (String) session.getAttribute("errorMesg");
		session.setAttribute("errorMesg",errorMesg);
	}				
    
    if(newUser){
    	%>
    		<jsp:forward   page="home.jsp"/>
    	<%
    }else{
    	%>
			<jsp:forward   page="register.jsp"/>
		<%
    }
	%>

